from random import randint

from django.contrib.auth import authenticate

from utils.example.SendMessage import Smsutil
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from utils.captcha.captcha import captcha


class ImageCodeView(View):
    def get(self, request, uuid):
        print(uuid)
        text, image = captcha.generate_captcha()
        print(text)

        redis_cli = get_redis_connection("code")
        redis_cli.setex(uuid, 120, text)

        return HttpResponse(image, content_type='image/jpeg')


class SmsCodeView(View):

    def get(self, request, mobile):
        #  - 注意++++++-+-+-+-+-
        #  从redis取出的redis_image_code
        #  是二进制的需要decode

        #  - ** 不要忘记
        #  删除图片验证码 **

        #  - 1
        #  获取参数
        image_code = request.GET.get("image_code")
        uuid = request.GET.get("image_code_id")
        #  - 2
        #  验证参数
        #  参数是否存在
        if not all([image_code, uuid]):
            return JsonResponse({"code": 400, "errmsg": "参数有误"})

        #  -  3
        #  验证图片验证码

        #  - 3.1
        #  根据uuid取出保存在redis里的验证码
        redis_cli = get_redis_connection("code")
        redis_image_code = redis_cli.get(uuid)
        try:
            redis_cli.delete(uuid)
        except Exception as e:
            print("删除图片验证码")
        #  - 3.2
        #  判断是否过有效期
        print("-------------", redis_image_code)
        if redis_image_code is None:
            return JsonResponse({"code": 400, "errmsg": "图片验证码过期了"})
        #  - 3.3
        #  用户发过来的对比redis_image_code是二进制需要decode
        if redis_image_code.decode().lower() != image_code.lower():
            return JsonResponse({"code": 400, "errmsg": "图片验证码输入错误"})

        #  - 4
        #  生成短信验证码
        sms_code = "%06d" % randint(0, 999999)
        print("sms_code", sms_code)

        # 防止频繁发送短信
        send_flag = redis_cli.get("send_flag_%s" % mobile)
        if send_flag:
            return JsonResponse({"code": 400, "errmsg": "短信发送过于频繁"})

        # 创建redis管道
        p1 = redis_cli.pipeline()
        #  保存短信验证码到rediskey的格式sms_手机号
        p1.setex("sms_%s" % mobile, 300, sms_code)

        p1.setex("send_flag_%s" % mobile, 60, 1)
        #  - 5

        p1.execute()
        # authenticate

        #  - 6
        #  发送短信
        # Smsutil().send_message(mobile, (sms_code, 5))
        from celery_tasks.sms.takes import celery_send_sms_code
        celery_send_sms_code.delay(mobile, sms_code)
        #  - 7
        #  返回响应
        return JsonResponse({"code": 0, "errmsg": "ok"})
